﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.IO;
using System.Xml;

using SourceGrid;
using Elegant.Ui;
using iPdf.Properties;

namespace iPdf
{
    abstract class TataRibbonPage: RibbonTabPage
    {
        #region Fields
        protected Collection<TataGrid.TataGridColumnInfo> visibleColumns;

        protected static CertificateDropDown Certificate;

        protected iPdf.HoverSelectionTextBox CertificatePassword;

        protected List<string> itemList = new List<string>();
        #endregion

        #region Properties

        public virtual PdfLetOption PdfLets
        {
            get
            {
                return PdfLetOption.NoPdfLets;
            }
        }


        protected virtual string DestinationSuffix
        {
            get
            {
                return string.Empty;
            }
        }

        public virtual FileFormat SourceFormat
        {
            get
            {
                return FileFormat.PdfFormat;
            }
        }

        public virtual FileFormat DestinationFormat
        {
            get
            {
                return FileFormat.PdfFormat;
            }
        }

        public virtual bool ReadyToAct
        {
            get
            {
                return Global.Grid.HasItems;
            }
        }

        public virtual bool OrderMatters
        {
            get
            {
                return false;
            }
        }

        public bool HasOptionGroup
        {
            get
            {
                return visibleColumns.Contains(Global.Grid.Destination) ||
                    PdfLets != PdfLetOption.NoPdfLets;
            }
        }

        public virtual bool PrinterDependent
        {
            get
            {
                return false;
            }
        }

        public virtual string ActionName
        {
            get
            {
                string pageName = this.GetType().Name;
                return pageName.Substring(0, pageName.IndexOf("Page", StringComparison.OrdinalIgnoreCase));
            }
        }

        public string DefaultSessionName
        {
            get
            {
                return ActionName;
            }
        }

        public bool HasNonCommonGroup
        {
            get
            {
                bool isCommonGroup = false;
                for (int i = this.Controls.Count - 1; i >= 0; i--)
                {
                    RibbonGroup group = (RibbonGroup) this.Controls[i];
                    foreach (RibbonGroup commonGroup in Global.MainWindow.CommonGroups)
                    {
                        if (commonGroup != group)
                        {
                            isCommonGroup = false;
                            continue;
                        }
                        else
                        {
                            isCommonGroup = true;
                            break;
                        }
                    }

                    if (isCommonGroup == false)
                    {
                        return true;
                    }
                }

                return false;
            }
        }

        public virtual bool SessionEnabled
        {
            get
            {
                return HasNonCommonGroup;
            }
        }

        public virtual bool SelectionSensitive
        {
            get
            {
                return false;
            }
        }

        public List<string> ItemList
        {
            get
            {
                return itemList;
            }
        }

        public virtual string HelpInfo
        {
            get
            {
                if (SessionEnabled)
                {
                    return global::iPdf.Properties.Resources.SessionPanelHelpInfo;
                }
                return string.Empty;
            }
        }

        public virtual string IntroInfo
        {
            get
            {
                return string.Empty;
            }
        }

        #endregion

        #region Ctor
        static TataRibbonPage()
        {
            Certificate = new CertificateDropDown();
            Certificate.Name = "Certificate";
        }

        public TataRibbonPage()
            :base()
        {
            visibleColumns = new Collection<TataGrid.TataGridColumnInfo>();
            visibleColumns.Add(Global.Grid.Id);
            visibleColumns.Add(Global.Grid.Source);
            visibleColumns.Add(Global.Grid.Status);
            
            InitializeComponent();
            InstallEventHandlers();
        }
        #endregion

        #region Internal methods

        protected virtual void InstallEventHandlers()
        {
        }


        protected virtual void LoadCertificateSubgroup()
        {
        }

        protected void SaveSession()
        {
            if (!Global.Grid.HasItems || !this.SessionEnabled)
            {
                return;
            }

            string name = DefaultSessionName;
            string fileName = TataSession.SessionsDir + name + Global.XmlExt;
            int count = 0;

            XmlDocument xmlDoc;
            XmlElement sessionNode = TataSession.CreateSessionNode(out xmlDoc);
            while (File.Exists(fileName))
            {
                if (TataSession.EqualSessionNode(sessionNode,
                                TataSession.ExtractSessionNode(fileName)))
                {
                    //duplicated session, stop
                    return;
                }

                ++count;
                name = DefaultSessionName + count.ToString();
                fileName = TataSession.SessionsDir + name + Global.XmlExt;
            }

            TataSession.ExportSession(fileName, string.Empty, xmlDoc);
        }

        protected void TextBox_TextChanged(object sender, EventArgs e)
        {
            UpdatePageOnlyControls();
            Global.MainWindow.UpdateActionGroup();
        }

        protected virtual void InitializeComponent()
        {
            this.CertificatePassword = new iPdf.HoverSelectionTextBox();
            // 
            // CertificatePassword
            // 
            this.CertificatePassword.Id = "48a22697-9f74-41b0-acf6-6806b666ab72";
            this.CertificatePassword.ImeMode = System.Windows.Forms.ImeMode.Disable;
            this.CertificatePassword.InformativenessMinimumLevel = "Elegant.Ui.TextBoxInformativenessLevel:TextBoxWithLabel";
            this.CertificatePassword.LabelAreaWidthTemplate = "Owner Password";
            this.CertificatePassword.LabelText = "Cert Password";
            this.CertificatePassword.Location = new System.Drawing.Point(217, 50);
            this.CertificatePassword.Name = "CertificatePassword";
            this.CertificatePassword.PasswordChar = '●';
            this.CertificatePassword.Size = new System.Drawing.Size(211, 24);
            this.CertificatePassword.SmallImages.Images.AddRange(new Elegant.Ui.ControlImage[] {
            new Elegant.Ui.ControlImage("Normal", global::iPdf.Properties.Resources.CertificatePassword16)});
            this.CertificatePassword.TabIndex = 4;
            this.CertificatePassword.TextChanged += new EventHandler(TextBox_TextChanged);
            this.CertificatePassword.TextEditorWidth = 95;
            this.CertificatePassword.UseSystemPasswordChar = true;
        }

        protected static void SetXmlElementAttribute(XmlElement xmlEle, string name, string value)
        {
            if (string.IsNullOrEmpty(name) 
                || string.IsNullOrEmpty(value))
            {
                return;
            }

            xmlEle.SetAttribute(name, value);
        }

        protected static void SetComboBoxBySession(XmlElement sessionNode, Elegant.Ui.ComboBox box)
        {
            int? index = Helper.ParseInt(sessionNode.GetAttribute(box.Name));
            if (index != null && index > 0 && index <= box.Items.Count)
            {
                box.SelectedIndex = (int)index - 1;
            }
        }

        protected static void SetCheckBoxBySession(XmlElement sessionNode, Elegant.Ui.CheckBox box)
        {
            box.Checked = Helper.ParseBool(sessionNode.GetAttribute(box.Name));
        }

        #endregion

        #region Public methods

        public virtual void UpdatePageOnlyControls()
        {
        }

        public virtual bool IsValidItem(string item)
        {
            if (string.IsNullOrEmpty(item) || !File.Exists(item))
            {
                return false;
            }

            FileInfo fileInfo = new FileInfo(item);
            if (string.IsNullOrEmpty(fileInfo.Extension))
            {
                return false;
            }

            return SourceFormat.IsOneOf(item);
        }

        public bool IsColumnVisible(TataGrid.TataGridColumnInfo colHead)
        {
            return visibleColumns.Contains(colHead);
        }

        public virtual string GetDestination(string item, string outputFolder)
        {
            if (string.IsNullOrEmpty(outputFolder))
            {
                outputFolder = Global.MainWindow.DefaultOutputFolder;
            }
            return Path.Combine( outputFolder, Path.GetFileNameWithoutExtension(item) + 
                        DestinationSuffix + DestinationFormat.Extension);
        }

        public void UpdatePage()
        {
            UpdatePageOnlyControls();
        }

        public void StartAction()
        {
            if (!ReadyToAct)
            {
                return;
            }

            SaveSession();

            Global.MainWindow.Status = WorkStatus.Busy;
            Global.MainWindow.UpdateRibbon();
            Global.MainWindow.UpdateGrid();
            Global.MainWindow.UpdateNotifyIconMenu();

            DoAction();
        }

        protected abstract void DoAction();

        public virtual void OnTabPageChanged()
        {
            if (!Global.Grid.HasItems)
            {
                foreach (string item in itemList)
                {
                    Global.Grid.AddItem(item, false);
                }
            }
            else
            {
                itemList.Clear();
            }
        }

        public static void SaveCertificates()
        {
            Certificate.StoreCertificates();
        }

        public virtual void SavePageOnlyData()
        {
        }

        public virtual void ImportSession(XmlElement sessionNode)
        {
        }

        public virtual void ExportSession(XmlElement sessionNode)
        {
        }

        public static void InstallHandlersForActor(EventHandler<ProcessItemEventArgs> itemStartedHandler,
                            EventHandler<ProcessItemEventArgs> itemFinishedHandler,
                            EventHandler<ProcessItemEventArgs> allItemsFinishedHandler)
        {
            VirtualActor.ItemStarted += itemStartedHandler;
            VirtualActor.ItemFinished += itemFinishedHandler;
            VirtualActor.AllItemsFinished += allItemsFinishedHandler;
        }

        public virtual void Load()
        {
        }

        public virtual int GetNumberOfPagesOfSourceFile(string fileName)
        {
            return SharpHelper.GetNumberOfPagesOfPdfFile(fileName);
        }

        #endregion


    }
}
